import { ref } from 'vue';
import { useWorkflowStore } from '@/stores/workflow';

// 创建全局单例状态
const isEnabled = ref(false);
let instance: ReturnType<typeof createKeydownManager> | null = null;

// 创建键盘事件管理器
const createKeydownManager = () => {
  const workflowStore = useWorkflowStore();

  const handleKeyDown = (e: KeyboardEvent) => {
    if (!isEnabled.value) return;

    // 如果正在输入，不处理快捷键
    if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) {
      return;
    }

    // Delete/Backspace 删除选中的节点和组
    if (e.key === 'Delete' || e.key === 'Backspace') {
      // 删除选中的节点
      if (workflowStore.state.selectedNodeIds.length > 0) {
        workflowStore.state.selectedNodeIds.forEach(nodeId => {
          // 先删除与该节点相关的所有连接
          const nodeConnections = workflowStore.state.connections.filter(conn => {
			const sourceMatch = conn.sourcePortId.match(/(?:input|output)-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i);
			const targetMatch = conn.targetPortId.match(/(?:input|output)-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i);
			const sourceNodeId = sourceMatch ? sourceMatch[1] : '';
			const targetNodeId = targetMatch ? targetMatch[1] : '';
            return sourceNodeId === nodeId || targetNodeId === nodeId;
          });
          
          nodeConnections.forEach(conn => {
            workflowStore.removeConnection(conn.id);
          });
		  
          // 从组中移除节点
          workflowStore.state.groups.forEach(group => {
            const index = group.nodeIds.indexOf(nodeId);
            if (index !== -1) {
              group.nodeIds.splice(index, 1);
            }
          });
          
          // 删除节点
          const nodeIndex = workflowStore.state.nodes.findIndex(node => node.id === nodeId);
          if (nodeIndex !== -1) {
            workflowStore.state.nodes.splice(nodeIndex, 1);
          }
        });
      }

      // 删除选中的组
      if (workflowStore.state.selectedGroupIds.length > 0) {
        workflowStore.state.selectedGroupIds.forEach(groupId => {
          const groupIndex = workflowStore.state.groups.findIndex(group => group.id === groupId);
          if (groupIndex !== -1) {
            workflowStore.state.groups.splice(groupIndex, 1);
          }
        });
      }
	  
	  // 删除选中的连接线
	  if (workflowStore.state.selectedConnectionIds.length > 0) {
	    workflowStore.state.selectedConnectionIds.forEach(connectionId => {
	      workflowStore.removeConnection(connectionId);
	    });
		workflowStore.state.selectedConnectionIds=[]
	  }
	  
      // 清除选中状态
      workflowStore.clearSelection();
      // 更新版本触发重渲染
      workflowStore.incrementVersion();
    }


    // 创建组
    if (e.key === 'c' && workflowStore.state.selectedNodeIds.length > 0) {
      e.preventDefault();
      workflowStore.addGroup('Group Node');
    }
  };
  
  const handleKeyUp = (_e: KeyboardEvent) => {
  };

  // 启用键盘事件
  const enable = () => {
    if (isEnabled.value) return;
    isEnabled.value = true;
    window.addEventListener('keydown', handleKeyDown);
    window.addEventListener('keyup', handleKeyUp);
  };

  // 禁用键盘事件
  const disable = () => {
    isEnabled.value = false;
    window.removeEventListener('keydown', handleKeyDown);
    window.removeEventListener('keyup', handleKeyUp);
  };

  // 切换启用状态
  const toggle = () => {
    if (isEnabled.value) {
      disable();
    } else {
      enable();
    }
  };

  return {
    isEnabled,
    enable,
    disable,
    toggle
  };
};

// 导出全局单例的获取方法
export const useKeydownManage = () => {
  if (!instance) {
    instance = createKeydownManager();
  }
  return instance;
};
